<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from "vue";
import api from "@/api";
import {
  type MachineDTO,
  type MachineGroupDTO,
  MachineGroupPageQry,
  MachinePageQry,
  type PageDTO
} from "@/types";
import { useRouter } from "vue-router";
import "@/assets/base-list.scss";
import "@/assets/form.scss";
import MachineSave from "@/views/machine/MachineSave.vue";
import MachineScriptExec from "@/views/machine/MachineScriptExec.vue";
import { useDelete } from "@/hooks";

interface State {
  loading: boolean;
  qry: MachinePageQry;
  machineGroupList: MachineGroupDTO[];
  result: PageDTO<MachineDTO>;
  crmContentSearchControlExpand: boolean;
  multipleMachine: MachineDTO[];
}

const machineSaveRef = ref<InstanceType<typeof MachineSave>>();
const machineScriptExecRef = ref<InstanceType<typeof MachineScriptExec>>();

const router = useRouter();

const state = reactive<State>({
  crmContentSearchControlExpand: false,
  loading: false,
  qry: new MachinePageQry(),
  machineGroupList: [],
  multipleMachine: [],
  result: {
    data: [],
    totalSize: 0,
    current: 1,
    size: 10,
    totalPage: 0
  }
});

const loadGroupList = () => {
  api.machineGroup
    .getMachineGroupList({
      size: 1000,
      current: 1
    })
    .then((res) => {
      state.machineGroupList = res.data.data;
    });
};

const loadData = () => {
  state.loading = true;
  api.machine
    .getMachinePage(state.qry)
    .then((res) => {
      state.result = res.data;
    })
    .finally(() => {
      state.loading = false;
    });
};

const reset = () => {
  state.qry = new MachinePageQry();
  loadData();
};

const handleBatchDelete = () => {
  useDelete(() =>
    api.machine.batchDelete({ ids: state.multipleMachine.map((item) => item.id) })
  ).then(loadData);
};

const handleBatchExecScript = () => {
  const ids = state.multipleMachine.map((item) => item.id);

  machineScriptExecRef.value?.openDialog(ids);
};

const handlePageSizeChange = () => {
  state.qry.current = 1;
  loadData();
};

const openTerminal = (id: string) => {
  const { href } = router.resolve({
    name: "terminal",
    query: {
      id: id
    }
  });
  window.open(href, "_blank");
};

const handleDelete = (row: MachineDTO) => {
  useDelete(() => api.machine.deleteMachine(row.id)).then(loadData);
};

const handleSelectionChange = (val: MachineDTO[]) => {
  state.multipleMachine = val;
};

const isBatch = computed(() => {
  return state.multipleMachine.length > 0;
});

onMounted(() => {
  loadGroupList();
  loadData();
});
</script>

<template>
  <el-form
    :model="state.qry"
    :inline="true"
    label-width="110px"
    class="crm-content__search overwrite-form"
  >
    <div class="crm-content__search__condition">
      <div class="crm-content__search__condition__main">
        <el-form-item label="分组：" class="el-form-item-width">
          <el-select v-model="state.qry.groupId" @change="loadData" placeholder="请选择" clearable>
            <el-option
              @keyup.enter="loadData"
              v-for="item in state.machineGroupList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称：" class="el-form-item-width">
          <el-input v-model="state.qry.nameLike" @keydown.enter="loadData" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="IP：" class="el-form-item-width">
          <el-input v-model="state.qry.ipLike" @keydown.enter="loadData" placeholder="请输入" />
        </el-form-item>
      </div>
      <div class="crm-content__search__condition__main" v-if="state.crmContentSearchControlExpand">
        <el-form-item label="用户名：" class="el-form-item-width">
          <el-input
            v-model="state.qry.usernameLike"
            @keydown.enter="loadData"
            placeholder="请输入"
          />
        </el-form-item>
        <div></div>
        <div></div>
      </div>
    </div>
    <div class="crm-content__search__control">
      <el-button type="primary" @click="loadData" icon="Search"> 查询</el-button>
      <el-button @click="reset" icon="Refresh"> 重置</el-button>
      <el-link
        :underline="false"
        @click="state.crmContentSearchControlExpand = !state.crmContentSearchControlExpand"
      >
        {{ state.crmContentSearchControlExpand ? "收起" : "展开" }}
        <el-icon v-if="state.crmContentSearchControlExpand">
          <ArrowUp />
        </el-icon>
        <el-icon v-if="!state.crmContentSearchControlExpand">
          <ArrowDown />
        </el-icon>
      </el-link>
    </div>
  </el-form>
  <div p-2>
    <el-button type="primary" @click="machineSaveRef?.openDialog()">新建</el-button>
    <el-button type="danger" @click="handleBatchDelete" :disabled="!isBatch">批量删除</el-button>
    <el-button @click="handleBatchExecScript" :disabled="!isBatch">批量执行脚本</el-button>
  </div>
  <el-table
    flex-1
    :data="state.result.data"
    v-loading="state.loading"
    border
    stripe
    resizable
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="name" label="名称"></el-table-column>
    <el-table-column prop="groupName" label="分组"></el-table-column>
    <el-table-column prop="ip" label="IP"></el-table-column>
    <el-table-column prop="username" label="用户名"></el-table-column>
    <el-table-column prop="port" label="端口"></el-table-column>
    <el-table-column min-width="200" label="操作">
      <template #default="scope">
        <el-button type="primary" size="small" @click="openTerminal(scope.row.id)">终端 </el-button>
        <el-button size="small" @click="machineSaveRef?.openDialog(scope.row.id)"> 编辑 </el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    size="small"
    background
    layout="total, prev, pager, next, sizes, jumper"
    :total="state.result.totalSize"
    v-model:page-size="state.qry.size"
    v-model:current-page="state.qry.current"
    @update:current-page="loadData"
    @update:page-size="handlePageSizeChange"
    p-5
  />
  <machine-save ref="machineSaveRef" @success="loadData" />
  <machine-script-exec ref="machineScriptExecRef" />
</template>
<style lang="scss" scoped>
.el-table__body-wrapper {
  overflow-y: scroll;
}
</style>
